package com.bckj.fastboot.upms.api.util.user;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.bckj.fastboot.core.lang.func.VoidFunc2;
import com.bckj.fastboot.upms.api.entity.SysUser;
import com.bckj.fastboot.upms.api.service.SysUserRemoteService;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class UserResolver {

    /**
     * 填充用户信息
     * @param list 数据
     * @param userIdGetter userId获取器
     * @param handle 处理器
     * @param <T> 数据泛型
     */
    public static <T> void fullSysUserInfo(List<T> list, Function<T, Long> userIdGetter, VoidFunc2<T, SysUser> handle) {
        fullSysUserInfo(list, new Function[] {userIdGetter}, new VoidFunc2[] {handle});
    }

    /**
     * 填充用户信息
     * @param list 数据
     * @param userIdGetterArray userId获取器数组
     * @param handleArray 处理器数组
     * @param <T> 数据泛型
     */
    public static <T> void fullSysUserInfo(List<T> list, Function<T, Long>[] userIdGetterArray, VoidFunc2<T, SysUser>[] handleArray) {
        Set<Long> userIds = new HashSet<>();
        for (T data : list) {
            for (Function<T, Long> userIdGetter : userIdGetterArray) {
                Optional.ofNullable(userIdGetter.apply(data)).ifPresent(userIds::add);
            }
        }
        Set<SysUser> users = SpringUtil.getBean(SysUserRemoteService.class).findByIds(userIds);
        if (CollUtil.isNotEmpty(users)) {
            Map<Long, SysUser> userMap = users.stream().collect(Collectors.toMap(SysUser::getId, Function.identity()));
            list.forEach(p -> {
                for (int i = 0; i < userIdGetterArray.length; i ++) {
                    SysUser su = Optional.ofNullable(userIdGetterArray[i].apply(p)).map(userMap::get).orElse(null);
                    if (su != null) {
                        handleArray[i].call(p, su);
                    }
                }
            });
        }
    }
}
